package com.rulin.asp.business.externalservice.uploadapi.controller;

import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rulin.asp.business.externalservice.uploadapi.entity.BookErrors;
import com.rulin.asp.business.externalservice.uploadapi.service.UploadBookErrorsService;
import com.rulin.asp.business.externalservice.util.AspResponse;

@Controller
@RequestMapping("/external")
public class UploadAPIController {
	
	@Autowired
	private UploadBookErrorsService uploadBookErrorsService;
	
	@RequestMapping(value = "/batchUploadError", method = RequestMethod.POST)
	@ResponseBody
	public AspResponse batchUploadErrors(@RequestBody String questions) {
		AspResponse response = new AspResponse();
		ObjectMapper objectMapper = new ObjectMapper();
		JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, BookErrors.class);
		try {
			List<BookErrors> list = objectMapper.readValue(questions, javaType);
			response = uploadBookErrorsService.uploadBookErrors(list);
		} catch (IOException e) {
			response.setCode(AspResponse.SERVER_ERROR);
			String message = e.getCause()==null ? e.getMessage() : e.getCause().getMessage();
			response.setMessage(message);
			response.setErrorMessage(e.getMessage());
		} catch (Exception e) {
			response.setCode(AspResponse.SERVER_ERROR);
			String message = e.getCause()==null ? e.getMessage() : e.getCause().getMessage();
			response.setMessage(message);
			response.setErrorMessage(e.getMessage());
		}
		return response;
	}
}
